package com.example.asset.exception;

import com.example.asset.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定义异常
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends RuntimeException{
    /**
     * 如果抛出的的是ServiceException，则调用该方法
     *
     * @param se 业务异常
     * @return Result
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result handle(ServiceException se, HttpServletRequest request, HttpServletResponse response){
        switch(se.getCode()){
            case 401:
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                break;
        }
        log.error(se.getMessage());
        return Result.error(se.getCode(), se.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handle(Exception se, HttpServletRequest request, HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error("未知异常", se);
        return Result.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, se.getMessage());
    }
}